<template>
  <div class="cardCollageChooseCarmi">
    <el-link v-if="isQuery" :underline="true" :style="{ color: '#135d1b', fontSize: '15px', paddingLeft: '25px' }"
      @click="handleSpanClick()">分类选择</el-link>
    <el-divider :style="{ margin: '10px 0' }" />
    <el-card shadow="hover">
      <el-form ref="queryFormRef" :model="queryCarmiParams" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item prop="cardName" style="width: 500px">
              <el-input v-model="queryCarmiParams.name" :rows="2" maxlength="50" show-word-limit
                placeholder="输入卡密的名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜 索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div v-if="isQuery">
      <el-table v-loading="loading" :data="data.cardMiNameList" max-height="500px" border>
        <el-table-column type="index" width="60" align="center" label="序号"></el-table-column>
        <el-table-column prop="cardName" align="center" label="卡密名称" width="600px"></el-table-column>
        <el-table-column prop="cardMi" align="center" label="操作">
          <template #default="scope">
            <el-link type="primary" :underline="false" style="margin-right: 30px;"
              @click="handleSubmit(scope.row)">选择</el-link>
            <el-link type="primary" :underline="false" @click="handlePreview(scope.row)">预览</el-link>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryCarmiParams.pageNum"
        v-model:limit="queryCarmiParams.pageSize" @pagination="getListByName" />
    </div>
    <div class="cardCollageChooseCarmi" v-if="!isQuery">
      <el-card style="margin-top: 20px">
        <el-form v-if="cardCategorySeriesList.length > 0" :model="form" ref="categoryFormRef" :rules="rules">
          <el-form-item prop="selectedItemId">
            <el-tree style="width: 600px" :data="cardCategorySeriesList" node-key="id" :load="loadNode" lazy
              :props="{ label: 'label', isLeaf: 'leaf' }">
              <template #default="{ node, data }">
                <div style="display: flex;align-items: center; width: 500px;justify-content: space-between;">
                  <div style="width: 200px;line-height: 14px;">
                    <el-tooltip class="box-item" effect="light" :content="node.label" placement="top-start">
                      <el-text truncated>{{ node.label }}</el-text>
                    </el-tooltip>
                  </div>
                  <div v-if="data.leaf" style="margin-left: 40px;">
                    <div style="display: flex; align-items: center;">
                      <el-link type="primary" :underline="false" style="margin-right: 30px;"
                        @click="handleSubmit(data)">选择</el-link>
                      <el-link type="primary" :underline="false" @click="handlePreview(data)">预览</el-link>
                    </div>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="footerButton" style="margin-top: 30px">
      <el-button @click="cancle">取 消</el-button>
    </div>
  </div>

  <el-dialog title="预览卡密" v-model="previewDiaLog.visible" width="1000px" append-to-body top="3vh" destroy-on-close>
    <div>
      <el-table v-loading="carmiLoading" :data="data.carmiInfoPreview" height="450px" border>
        <el-table-column type="index" width="60" align="center" label="序号"></el-table-column>
        <el-table-column prop="carmiInfo" align="center" label="卡密信息" width="1000px"></el-table-column>
      </el-table>
      <pagination v-show="carmiTotal > 0" :total="carmiTotal" v-model:page="queryCarmiInfoParams.pageNum"
        v-model:limit="queryCarmiInfoParams.pageSize" @pagination="preview" />
    </div>
  </el-dialog>
</template>
<script lang=ts setup>
import { ref, reactive, toRefs, watch } from 'vue'
import { queryCardCaCtegoryBySeries, queryCardCaCtegoryType, queryCardCategoryByName, previewCard } from '@/api/workflow/category/index'
import { CardCollageVO } from '@/api/workflow/cardCollage/types';
import { CardCategorySeriesVo } from '@/api/workflow/category/types';
import { get } from '@vueuse/core';
const loading = ref(true);
const carmiLoading = ref(true);
const total = ref(0);
const carmiTotal = ref(0);
const cardCategorySeriesList = ref<CardCategorySeriesVo[]>([]);
const { proxy } = getCurrentInstance()
const isQuery = ref(false)
const previewCardId = ref()
const data = reactive({
  form: {
    selectedItemId: undefined,
  },
  queryCarmiParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  queryCarmiInfoParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    id: undefined,
  },
  rules: {
    selectedItemId: [{ required: true, message: '请选择卡密', trigger: 'blur' }],
  },
  results: [], // 用于存储接口返回的数据
  selectedItem: {},
  cardMiNameList: [],
  carmiInfoPreview: [],
})
const { form, queryCarmiParams,queryCarmiInfoParams, rules } = toRefs(data)
const previewDiaLog = reactive<DialogOption>({
  visible: false,
  title: '预览卡密'
});
const categoryFormRef = ref()

const props = defineProps({
  cardCategoryId: {
    type: [String, Number],
    default: undefined,
  },
})
const emit = defineEmits(['close', 'submit'])

/** 搜索按钮操作 */
const handleQuery = () => {
  getListByName()
  // try {
  //   const response = await fetchData(queryCarmiParams.cardName)
  //   data.results = response.data; // 按API返回结果结构更新数据
  // } catch (error) {
  //   console.error('Error fetching data:', error)
  // }
}

const getListByName = async () => {
  // const query = {
  //   cardName: queryCarmiParams.value.cardName
  // }
  loading.value = true;
  isQuery.value = true
  const res = await queryCardCategoryByName(queryCarmiParams.value);
  total.value = res.total;
  data.cardMiNameList = res.rows;
  loading.value = false;
}

const preview = async () => {
  try {
    carmiLoading.value = true;
    queryCarmiInfoParams.value.id = previewCardId.value;
    const res = await previewCard(queryCarmiInfoParams.value);
    carmiTotal.value = res.total;
    data.carmiInfoPreview = res.rows;
    carmiLoading.value = false;
  } catch (error) {
    console.error('预览失败:', error);
  }
}

const getList = async () => {
  const query = {}
  const res = await queryCardCaCtegoryBySeries(query);
  cardCategorySeriesList.value = res.rows.map((item: any) => {
    return {
      ...item,
      label: item.cardSeries,
      leaf: false,
    }
  });
  return res.rows
}

const getSecond = async (id?: string | number) => {
  const query = {
    series: id
  }
  const res = await queryCardCaCtegoryType(query);
  const data = res.rows.map((item: any) => {
    return {
      ...item,
      leaf: false,
      label: item.cardSubseries,
    }
  })
  return data;
}

const handleSpanClick = () => {
  isQuery.value = false;
}

const getThird = async (series?: string | number, subSeries?: string | number) => {
  let query = {
    series: series,
    subSeries: subSeries,
    pageSize: -1,
    pageNum: -1,
  }

  let res = await queryCardCategoryByName(query)
  let data = res.rows.map((item: any) => {
    return {
      ...item,
      label: item.cardName,
      leaf: true,
    }
  })
  return data
}

watch(() => props.cardCategoryId, (val) => {
  getList()
}, {
  deep: true,
  immediate: true,
})

const loadNode = async (node: any, resolve: any) => {
  if (node.level === 0) {
    return resolve(cardCategorySeriesList.value)
  }
  if (node.level === 1) {
    let res = await getSecond(node.data.cardSeries)
    return resolve(res)
  }
  if (node.level === 2) {
    let res = await getThird(node.data.cardSeries, node.data.cardSubseries)
    return resolve(res)
  }
}

const cancle = () => {
  emit('close')
}
const handleSubmit = (node: any) => {
  emit('submit', node)
}
const handlePreview = async (node: any) => {
  previewCardId.value = node.id;
  await preview();
  previewDiaLog.visible = true;
  previewDiaLog.title = "预览卡密";
}
</script>
<style lang="scss" scoped>
::v-deep(.el-scrollbar .el-scrollbar__wrap) {
  overflow-x: hidden;
}

::v-deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

.footerButton {
  display: flex;
  justify-content: center;
  align-self: center;
  text-align: center;
}
</style>
